package demo.controller;

import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;
import org.jweb.core.bean.ReplyDataMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import cn.keepme.ep.common.service.SysServiceI;

import com.alibaba.fastjson.JSONObject;

@ServerEndpoint(value = "/notifywebsocket",configurator = SpringConfigurator.class)
@Controller
public class NotifyWebSocket {
	private static final Logger logger = Logger.getLogger(NotifyWebSocket.class);
	
	@Autowired
	private SysServiceI sysService;
	

	@SuppressWarnings("unchecked")
	@OnMessage
	public void onMessage(String message, Session session) {
		logger.info("Received id: " + message);
		String  mphone = message;
		ReplyDataMode replyDataMode = new ReplyDataMode();
		String id = null;// 记录ID 是否两次相同
		Map<String, Object> map = null;
		int count = 0;// 判断是否第一次，第一次不需要进行消息推送
		try{
			while (true) {
				Thread.sleep(5000);
				String sql = "select * from tp_notify t  where EXISTS(select 1 from tp_user_category us join tp_analyze_category ac on ac.id = us.category_id where    us.status ='1' and us.general_user_id = '" + mphone + "' and t.category_code = ac.category_name)  ORDER BY t.create_date desc limit 0,1";
				map = sysService.findOneForJdbc(sql, null);
				logger.info(map);
				if (map != null) {
					// 第一次ID初始化
					if (count == 0) {
						id = map.get("id").toString();
					}
					// 判断当前是否已推送
					if (count != 0 && !id.equals(map.get("id").toString())) {
					
						id = map.get("id").toString();
						if(session!=null){
							replyDataMode.setData(map);
							replyDataMode.setSuccess(true);
							String json = JSONObject.toJSONString(replyDataMode);
							session.getBasicRemote().sendText(json);
							count++;
						}
					}
					count++;
					// 重置
					if (count == 5000) {
						count = 1;
					}
	
				}
	
			}
		} catch(Exception e){
			
			e.printStackTrace();
			logger.info("Connection closed");
		} 
	}

	@OnOpen
	public void onOpen() {
		logger.info("Client connected");
	}

	@OnClose
	public void onClose() {
		logger.info("Connection closed");
	}

}
